const CabinetGrpServices = require("../services/cabinetsgrpServices");

class CabinetsGrpControllers {
  constructor() {
    // 绑定方法到当前实例
    this.addNewCabinetsGrp = this.addNewCabinetsGrp.bind(this);
    this.delCabinetsGrpById = this.delCabinetsGrpById.bind(this);
    this.updateCabinetsGrpById = this.updateCabinetsGrpById.bind(this);
    this.getCabinetsGrpById = this.getCabinetsGrpById.bind(this);
    this.getAllCabinetsGrps = this.getAllCabinetsGrps.bind(this);
    this.getMapofCabinetsGrps = this.getMapofCabinetsGrps.bind(this)
  }

  // 统一响应函数
  handleRequest = async (serviceMethod, req, res, successStatus = 200) => {
    try {
      const result = await serviceMethod(req);
      if (result.code === 0) {
        res.status(successStatus).json(result); // 成功
      } else {
        res.status(result.statusCode || 400).json(result); // 失败
      }
    } catch (error) {
      console.log(error);
      res.status(500).json({
        code: 1,
        msg: "服务器内部错误",
      });
    }
  };

  async addNewCabinetsGrp(req, res) {
    await this.handleRequest(
      () => CabinetGrpServices.addNewCabinetsGrp(req.body),
      req,
      res
    );
  }

  async delCabinetsGrpById(req, res) {
    await this.handleRequest(
      () => CabinetGrpServices.delCabinetsGrpById(req.params.id),
      req,
      res
    );
  }

  async updateCabinetsGrpById(req, res) {
    await this.handleRequest(
      () => CabinetGrpServices.updateCabinetsGrpById(req.params.id, req.body),
      req,
      res
    );
  }

  async getCabinetsGrpById(req, res) {
    await this.handleRequest(
      () => CabinetGrpServices.getCabinetsGrpById(req.params.id),
      req,
      res
    );
  }

  async getAllCabinetsGrps(req, res) {
    await this.handleRequest(
      () => CabinetGrpServices.getAllCabinetsGrps(),
      req,
      res
    );
  }

  async getMapofCabinetsGrps(req, res) {
    await this.handleRequest(
      () => CabinetGrpServices.getMapofCabinetsGrps(),
      req,
      res
    );
  }
}

module.exports = new CabinetsGrpControllers();
